package com.tsd.system.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.CommonMsgNameConstants;
import com.tsd.CommonParamNameConstants;
import com.tsd.core.annotation.DataPermission;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HttpResult;
import com.tsd.system.entity.SysGroup;
import com.tsd.system.entity.SysGroupExt;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import com.tsd.system.service.SysGroupService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tsd.core.constants.Constants.PARAMS_KEY_NAME_GROUP_PERMISSION;

/**
 * 描述：组织架构（部门）
 * 控制层
 *
 * @author Hillpool
 * 2019/03/12 12:20:51
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
public class SysGroupController extends SystemBaseController {

    @Resource
    private SysGroupService sysGroupService;

    @ApiOperation(value = "根据sid组织架构（部门）")
    @ResponseBody
    @RequestMapping(value = "/getSysGroupBySid.action", method = RequestMethod.POST)
    public HttpResult<Object> getSysGroupBySid() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, CommonParamNameConstants.SID);
            super.checkEmpty(sid, CommonMsgNameConstants.EMPTY_MSG_SID);
            SysGroup sysGroup = sysGroupService.getSysGroupBySid(sid);
            hr.setData(sysGroup);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "保存组织架构（部门）")
    @ResponseBody
    @RequestMapping(value = "/saveSysGroup.action", method = RequestMethod.POST)
    public HttpResult<Object> saveSysGroup() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser sysUser = this.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String json = JSON.toJSONString(map);
            SysGroup t = JSON.parseObject(json, SysGroup.class);
            sysGroupService.saveSysGroup(t, sysUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除组（单位、部门）信息")
    @ResponseBody
    @RequestMapping(value = "/deleteSysGroup.action", method = RequestMethod.POST)
    public HttpResult<Object> deleteSysGroup() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = this.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Object sids = map.get(CommonParamNameConstants.SIDS);
            super.checkEmpty(sids, CommonMsgNameConstants.EMPTY_MSG_SIDS);
            List<String> list = JSON.parseArray(JSON.toJSONString(sids), String.class);
            sysGroupService.deleteSysGroup(list, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "查询组织架构（部门）树")
    @ResponseBody
    @RequestMapping(value = "/findSysGroupTree.action", method = RequestMethod.POST)
    @DataPermission(code = "sysGroupTree")
    public HttpResult<Object> findSysGroupTree() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = super.getDataPermissionParams();
            Object obj = params.get(PARAMS_KEY_NAME_GROUP_PERMISSION);
            if (!params.isEmpty() && obj == null) {
                //如果已开通了权限但没有部门授权，则清空后将当前用户的部门加入
                //需要保证admin不属于某个部门，然后使用admin维护管理员的部门数据访问权限，这样才能进行正常授权
                params.clear();
                SysUserExt userExt = (SysUserExt) SecurityUtils.getSubject().getPrincipal();
                List<String> groupList = new ArrayList<>();
                if (!HlpUtils.isEmpty(userExt.getGroup_sid())) {
                    groupList.add(userExt.getGroup_sid());
                    params.put(PARAMS_KEY_NAME_GROUP_PERMISSION, groupList);
                }
            }
            HlpUtils.copyStringValue(map, params, CommonParamNameConstants.PARENT_SID, false, false);
            HlpUtils.copyIntegerValue(map, params, CommonParamNameConstants.DR, false, 0);
            List<SysGroupExt> list = sysGroupService.findSysGroupTree(params);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "查询所有组织架构（部门）树，不管权限")
    @ResponseBody
    @RequestMapping(value = "/findSysGroupTreeAll.action", method = RequestMethod.POST)
    public HttpResult<Object> findSysGroupTreeAll() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>();
            HlpUtils.copyStringValue(map, params, CommonParamNameConstants.PARENT_SID, false, false);
            HlpUtils.copyIntegerValue(map, params, CommonParamNameConstants.DR, false, 0);
            List<SysGroupExt> list = sysGroupService.findSysGroupTree(params);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
